package producerconsumer;

/**
 *Description:线程之间的通讯，旧的版本用wait,notify
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/23 21:20
 */
public class Old {

  public static void main(String[] args) {
    Calculate c = new Calculate();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.increasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"A").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.decreasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"B").start();


    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.increasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"C").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.decreasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"D").start();

  }

}
class Calculate {
  public int num=0;
  public synchronized void  increasing() throws InterruptedException {
    while (num!=0){
      wait();
    }
    num++;
    System.out.println(Thread.currentThread().getName()+"=>"+num);
    notifyAll();
  }
  public synchronized void decreasing() throws InterruptedException {
    //用while才能解决多个线程的等待
    while(num!=1){
      wait();
    }
    num--;
    System.out.println(Thread.currentThread().getName()+"=>"+num);
    notifyAll();
  }
}
